/*
 * tcpclient.cpp
 *
 *  Created on: 2017年6月15日
 *      Author: work
 */

#include <dm/os/io/tcpclient.hpp>

#include <dm/os/log/logger.hpp>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace dm{
namespace os{
namespace io{

static const char* logModule = "CTcpClient.io.os.dm";

CTcpClient::CTcpClient():CIo(){
	m_txBySend = true;
}

CTcpClient::type_t CTcpClient::type()const{
	return com::CAddress::TcpClient;
}

bool CTcpClient::open_in( const com::CAddress& addr ){
	const com::CTcpClientAddr* address = addr.asTcpClient();

	if( address ){
		m_fd = socket(AF_INET,SOCK_STREAM,0);
		if( m_fd<0 ){
			log().error(THISMODULE "不能创建socket");
			return false;
		}

		sockaddr_in servaddr;
		memset( &servaddr,0,sizeof(sockaddr_in));

		servaddr.sin_family = AF_INET;
		servaddr.sin_port = htons(address->getServerPort());
		servaddr.sin_addr.s_addr = inet_addr(address->getServerHost().c_str());

		if( connect(m_fd,(struct sockaddr*)&servaddr,sizeof(servaddr))!=0 ){
			perror(__FUNCTION__);
			log().info(THISMODULE "连接到%s:%d失败",address->getServerHost().c_str(),address->getServerPort());
			close();
			return false;
		}else{
			log().info(THISMODULE "连接到%s:%d成功",address->getServerHost().c_str(),address->getServerPort());
			return true;
		}
	}

	return false;
}

}
}
}


